package com.lottery.ruok.lottrey.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.ListView;

import com.applozic.mobicomkit.ChatConfig;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.GiveRewardDetailActivity;
import com.lottery.ruok.lottrey.adapter.PrizeRedPacketAdapter;
import com.lottery.ruok.lottrey.chat.model.prize.message.PrizeMessage;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.DaShangStatResquest;
import com.lottery.ruok.lottrey.retrofitModule.response.DaShangStatResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;

import utils.Utils;

public class GivePrizeFragment extends BaseFragment {
    @BindView(R.id.hongbao_list)
    ListView hongbao_list;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    private ArrayList<DaShangStatResponse.ListBean> listBeans = new ArrayList<>();
    private int mIndex = 0;
    private PrizeRedPacketAdapter myAdapter;
    private long CURRENT_YEAR = 0;//这里其实不严谨
    private View emptyLayout;

    private void setEmtpyView(){
        if (emptyLayout == null && getView() != null) {
            ViewStub stub = getView().findViewById(R.id.no_net_viewstub);
            View view = stub.inflate();
            emptyLayout = view.findViewById(R.id.no_net_view);
            emptyLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    getList(0);
                }
            });
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_give_prize, null);

        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init(){
        CURRENT_YEAR = Long.parseLong(Utils.toYear(System.currentTimeMillis()));

       /* BGARefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(getContext(), true);
        swipeRefreshLayout.setRefreshViewHolder(refreshViewHolder);

        swipeRefreshLayout.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                getList(mIndex);
                return true;
            }

            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                getList(0);
            }
        });*/
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mRefreshLayout.setEnableRefresh(true);//启用刷新
                getList(0);
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                mRefreshLayout.setEnableLoadMore(true);//启用加载
                getList(mIndex);
            }
        });
        getList(0);

        hongbao_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(listBeans.get(i).getType3().equals("打赏")){
                    Intent intent = new Intent(getActivity(), GiveRewardDetailActivity.class);
        /*            intent.putExtra("times", listBeans.get(i).getSubmit_time());
                    intent.putExtra(ChatConfig.REWARD_MONEY, listBeans.get(i).getAmount());
                    intent.putExtra(ChatConfig.REWARD_FROM, listBeans.get(i).getFrom_nickname());
                    intent.putExtra(ChatConfig.REWARD_TO, listBeans.get(i).getTo_nickname());
                    intent.putExtra(ChatConfig.REWARD_FROM_AVATAR,  listBeans.get(i).getFrom_avatar());
                    intent.putExtra(ChatConfig.REWARD_TO_AVATAR,  listBeans.get(i).getTo_avatar());*/

                    PrizeMessage prizeMessage = new PrizeMessage();
                    prizeMessage.setDate(dateToStamp(listBeans.get(i).getSubmit_time()));
                    prizeMessage.setSendUserNickname(listBeans.get(i).getFrom_nickname());
                    prizeMessage.setReceiveUserNickname(listBeans.get(i).getTo_nickname());
                    prizeMessage.setMoney(Double.valueOf(listBeans.get(i).getAmount()));
                    intent.putExtra("extra_prize_message",prizeMessage);
                    getContext().startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), GiveRewardDetailActivity.class);
                   /* intent.putExtra("times", listBeans.get(i).getSubmit_time());
                    intent.putExtra(ChatConfig.REWARD_MONEY, listBeans.get(i).getAmount());
                    intent.putExtra(ChatConfig.REWARD_TO, listBeans.get(i).getFrom_nickname());
                    intent.putExtra(ChatConfig.REWARD_FROM, listBeans.get(i).getTo_nickname());
                    intent.putExtra(ChatConfig.REWARD_TO_AVATAR,  listBeans.get(i).getFrom_avatar());
                    intent.putExtra(ChatConfig.REWARD_FROM_AVATAR,  listBeans.get(i).getTo_avatar());*/
                    PrizeMessage prizeMessage = new PrizeMessage();
                    prizeMessage.setDate(dateToStamp(listBeans.get(i).getSubmit_time()));
                    prizeMessage.setSendUserNickname(listBeans.get(i).getTo_nickname());
                    prizeMessage.setReceiveUserNickname(listBeans.get(i).getFrom_nickname());
                    prizeMessage.setMoney(Double.valueOf(listBeans.get(i).getAmount()));
                    intent.putExtra("extra_prize_message",prizeMessage);
                    getContext().startActivity(intent);
                }
            }
        });
    }

    private void getList(final int index){
        long year = CURRENT_YEAR - index;
        String start = year + "-01";
        String end = year + "-12";
        RetrofitBase.getRetrofit().create(DaShangStatResquest.class)
                .getResult(UserInfo.getToken(), UserInfo.getUsername(), start, end)
                .compose(RxHelper.<ArrayList<DaShangStatResponse>>handleResult())
                .subscribe(new RxSubscribe<ArrayList<DaShangStatResponse>>(getActivity()) {
                    @Override
                    protected void _onNext(ArrayList<DaShangStatResponse> daShangStatResponse) {
                        mIndex = index + 1;
                        if(index == 0){
                            listBeans.clear();
                        }

                        for(DaShangStatResponse list : daShangStatResponse){
                            if(list.getList().size() > 0){
                                float in = Float.parseFloat(list.getCash_in());
                                float out = Float.parseFloat(list.getCash_out());
                                float profit = in - out;
                                String profits;
                                if(profit > 0){
                                    profits = "+" + profit;
                                } else {
                                    profits = "" + profit;
                                }
                                list.getList().get(0).setDescp(list.getYear() + "-" + list.getMonth() + "  " + profits + "  " + "转入" + in + "转出" + out);
                            }
                            listBeans.addAll(list.getList());
                        }
                        if(index == 0){
                            if(getContext() != null) {
                                myAdapter = new PrizeRedPacketAdapter(getActivity(), listBeans);
                                hongbao_list.setAdapter(myAdapter);
                                mRefreshLayout.finishRefresh();
                            }
                        } else {
                            myAdapter.notifyDataSetChanged();
                            mRefreshLayout.finishLoadMore();
                        }

                        if(listBeans.size() == 0) {
                            setEmtpyView();
                        } else {
                            if(emptyLayout != null){
                                emptyLayout.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);

                        if(index == 0){
                            if(mRefreshLayout != null){
                                mRefreshLayout.finishRefresh();
                            }
                        } else {
                            if(mRefreshLayout != null){
                                mRefreshLayout.finishLoadMore();
                            }
                        }

                        if(listBeans != null){
                            if(listBeans.size() == 0) {
                                setEmtpyView();
                            }
                        }
                    }
                });
    }
    private static String dateToStamp(String s) {
        String res = "";
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = simpleDateFormat.parse(s);
            long ts = date.getTime();
            res = String.valueOf(ts);
        } catch (ParseException e) {
        }
        return res;
    }
}
